package com.mirzabros.chexmo.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.mirzabros.chexmo.Chexmo_Webview;
import com.mirzabros.chexmo.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;

public class Chexmo_Register_Service extends AsyncTask<String, Void, String> {

	private ProgressDialog progdialod;
	private Activity activity;
	private Context context;

	public static Cookie cookie = null;

	private String storeName;
	private String email;
	private String password;
	private String promcode;
	private String code;
	private String timeZone;
	private String country;
	private String usd;

	// connection establish timeout (timeoutConnection)
	private int timeoutConnection = 5000;
	// socket timeout (timeoutSocket)
	private int timeoutSocket = 45000;

	JSONArray jArray;

	private boolean exeption = false;

	static InputStream is = null;
	static JSONObject jobj = null;
	static String json = "";
	List<NameValuePair> params;
	HttpParams httpParameters = new BasicHttpParams();

	public Chexmo_Register_Service(Activity activity, String store,
			String email, String password, String promcode, String code,
			String timezone, String country, String usd) {
		super();
		this.activity = activity;
		this.context = this.activity.getApplicationContext();
		this.storeName = store;
		this.password = password;
		this.email = email;
		this.promcode = promcode;
		this.code = code;
		this.timeZone = timezone;
		this.country = country;
		this.usd = usd;

		Log.d("userName", store);
		Log.d("country", country);
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		progdialod = ProgressDialog.show(this.activity, "User Register",
				"Registering, Please Wait", true, false);
	}

	@Override
	protected String doInBackground(String... urls) {

		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

		try {

			HttpConnectionParams.setConnectionTimeout(httpParameters,
					timeoutConnection);
			HttpClient httpclient = new DefaultHttpClient(httpParameters);

			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("store", storeName));
			params.add(new BasicNameValuePair("pass", password));
			params.add(new BasicNameValuePair("mail", email));
			params.add(new BasicNameValuePair("field_promo_code", promcode));
			params.add(new BasicNameValuePair("field_store_link_code", code));
			params.add(new BasicNameValuePair("timezone", timeZone));
			params.add(new BasicNameValuePair("field_store_country", country));
			params.add(new BasicNameValuePair("field_store_currency", usd));

			/* HttpPost httppost = new HttpPost(RegisterUserLink); */
			HttpPost httppost = new HttpPost(urls[0]);
			JSONObject json = new JSONObject();

			json.put("store", storeName);
			json.put("pass", password);
			json.put("mail", email);
			json.put("field_promo_code", promcode);
			json.put("field_store_link_code", code);
			json.put("timezone", timeZone);
			json.put("field_store_country", country);
			json.put("field_store_currency", usd);

			JSONArray postjson = new JSONArray();
			postjson.put(json);
			httppost.setHeader("json", json.toString());

			Log.d("json.toString()", json.toString());

			httppost.getParams().setParameter("jsonpost", postjson);
			httppost.setEntity(new UrlEncodedFormEntity(params));
			HttpResponse httpResponse = httpclient.execute(httppost);

			HttpEntity httpEntity = httpResponse.getEntity();

			is = httpEntity.getContent();

		} catch (UnsupportedEncodingException e) {
			exeption = true;
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			exeption = true;
			e.printStackTrace();
		} catch (IOException e) {
			exeption = true;
			e.printStackTrace();
		} catch (JSONException e) {
			exeption = true;
			e.printStackTrace();
		}

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();

			String line = null;

			while ((line = reader.readLine()) != null) {
				// sb.append(line+"n");
				sb.append(line);
			}
			is.close();
			json = sb.toString();

			Log.e("JSON RES:", json);

		} catch (Exception e) {
			exeption = true;
			Log.e("Buffer Error", "Error converting result" + e.toString());
		}
		return json;

	}

	@Override
	protected void onPostExecute(String result) {

		Log.d("Post Exec", "POST EXEC");

		Log.d("Post tt", result);
		progdialod.dismiss();

		Log.d("Post Exec", result);

		if (result.trim().equals("fail")) {

			Toast toast = Toast.makeText(activity, "Register Failed !!",
					Toast.LENGTH_SHORT);
			toast.show();

		} else {
			if (!exeption) {

				if (result.length() < 9) {
					Toast toast = Toast.makeText(activity, "Success !!",
							Toast.LENGTH_SHORT);
					toast.show();

					Button btnloginmain = (Button) activity
							.findViewById(R.id.btnLogin);

					btnloginmain.performClick();
				}

				else if (!result.substring(0, 9).equals("<!DOCTYPE")) {

					Toast toast = Toast.makeText(activity, "Success !!",
							Toast.LENGTH_SHORT);
					toast.show();

					Button btnloginmain = (Button) activity
							.findViewById(R.id.btnLogin);

					btnloginmain.performClick();

					/*
					 * Intent intent = new
					 * Intent(activity,Chexmo_Webview.class);
					 * intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); Bundle
					 * bundle = new Bundle(); bundle.putString("user",
					 * storeName); bundle.putString("pass", password);
					 * bundle.putString("code", result);
					 * intent.putExtras(bundle); activity.startActivity(intent);
					 */
				} else {
					Toast toast = Toast.makeText(activity,
							"Register Failed Due to Exeption !!",
							Toast.LENGTH_SHORT);
					toast.show();
				}

			} else {
				Toast toast = Toast.makeText(activity,
						"Register Failed Due to Exeption !!",
						Toast.LENGTH_SHORT);
				toast.show();
			}

		}

		/*
		 * Toast toast = Toast.makeText(activity,
		 * "UserName Or Password Incorrect. Login Failed !!",
		 * Toast.LENGTH_SHORT); toast.show();
		 */

	}
}
